﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using NReader.Model.RAS;
using NReader.Service;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234237 上有介绍

namespace XnReader.WinRT
{
    /// <summary>
    /// 基本页，提供大多数应用程序通用的特性。
    /// </summary>
    public sealed partial class Chapter
    {
        private ChapterInfo _chapter;

        private SysWebInfo _webInfo;

        //private bool _isWebView;

        public Chapter()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            var chapterid = int.Parse(navigationParameter.ToString());
            //?san
            //_chapter = await ChapterService.GetChapterSession(chapterid);
            if (_chapter == null) return;

            DefaultViewModel["Chapter"] = _chapter;
            btnPrev.IsEnabled = _chapter.previewpage > 0;
            btnNext.IsEnabled = _chapter.nextpage > 0;
            //?san 获取最新章节？
            //await ChapterService.GetMaxChaptersLocal(_chapter.articleid);
            _webInfo = await GlobalService.Instance().GetSysWebInfoFromLocal(_chapter.webflag);
            var content = await ChapterService.GetChapterTxt(_chapter.webflag,_chapter.articleid,_chapter.chapterid);

            var needSave = false;
            var source = false;
            if (string.IsNullOrEmpty(content))
            {
                content = await GetHtmlContent();
                if (!string.IsNullOrEmpty(content))
                {
                    needSave = true;
                }
                else
                {
                    source = true;
                }
            }
            await ShowContent(content, source, false, needSave);
        }

        private async Task ShowContent(string content, bool source, bool primary, bool needSave)
        {
            pbLoading.IsActive = false;
            if (_chapter.webstate.Equals(3) || source) //参考数据库信息
            {
                ChapterContent.Navigate(typeof (ChapterWebView), string.Format("1{0}", _chapter.chapterlink));
                hlbLink.Visibility = Visibility.Collapsed;
            }
            else if ((primary && _chapter.webstate.Equals(1)) || _chapter.webstate.Equals(2))
            {
                content = ReplaceLinkText(content);
                ChapterContent.Navigate(typeof (ChapterWebView), string.Format("2{0}", content));
                hlbLink.Visibility = Visibility.Collapsed;
            }
            else if(_chapter.ctype.Equals(1)||HasImages(content))//图片章节，服务端验证+客户端验证
            {
                content = ReplaceLinkText(content);
                ChapterContent.Navigate(typeof(ChapterWebView), string.Format("2{0}", content));
                //ChapterContent.Navigate(typeof(ChapterWebView), string.Format("1{0}", _chapter.chapterlink));
                hlbLink.Visibility = Visibility.Collapsed;
            }
            else if (_chapter.ctype.Equals(0) && _chapter.webstate.Equals(1)) //txt
            {
                hlbLink.Visibility = Visibility.Visible;
                if (needSave)
                {
                    var temp= MatchChapterContent(content);
                    if (!string.IsNullOrEmpty(temp))
                    {
                        content = temp;
                        await Task.Run(() => ChapterService.SaveChapterTxt(_chapter.webflag,
                                                                           _chapter.articleid,
                                                                           _chapter.chapterid,
                                                                           content));
                    }
                    else//原版规则匹配出错
                    {
                        hlbLink.Visibility = Visibility.Collapsed;
                    }
                }
                ChapterContent.Navigate(typeof(ChapterTextView), content);
            }
            else //default
            {
                ChapterContent.Navigate(typeof (ChapterWebView), string.Format("1{0}", _chapter.chapterlink));
            }
        }

        protected override void SaveState(Dictionary<string, object> pageState)
        {
            pageState["Page"] = "Chapter";
        }

        #region Pop Bookreader

        private void BtnBookReaderClick(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(BookReader), _chapter.chapterid);
        }

        #endregion

        #region Http get html

        private HttpClient _httpClient;

        private async Task<string> GetHtmlContent()
        {
            if (_httpClient == null)
            {
                _httpClient = new HttpClient();
                //_httpClient.MaxResponseContentBufferSize = 25600;
                _httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
            }
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync(_chapter.chapterlink);
                response.EnsureSuccessStatusCode();
                var bytes = await response.Content.ReadAsByteArrayAsync();
                return Encoding.GetEncoding(_webInfo.encoding).GetString(bytes, 0, bytes.Length);
            }
            catch (HttpRequestException ex )
            {
                return string.Empty;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        private string MatchChapterContent(string html)
        {
            var match = Regex.Match(html, _webInfo.matchtext, RegexOptions.None);

            if (string.IsNullOrEmpty(match.Groups[1].Value)) return string.Empty;

            var result = match.Groups[1].Value;
            if (!string.IsNullOrEmpty(_webInfo.filtertext))
            {
                //[过滤方法：正则0，替换1]$[目标值/正则表达式]♂
                var arrs = _webInfo.filtertext.Split('♂');
                foreach (var arr in arrs)
                {
                    var splits = arr.Split('$');
                    if (splits.Count() >= 2)
                    {
                        result = splits[0].Equals("1") ? result.Replace(splits[1], string.Empty) : Regex.Replace(result, splits[1], string.Empty);
                    }
                }
            }
            return result;
        }

        private bool HasImages(string html)
        {
            var matchResult = Regex.Matches(html, _webInfo.matchimage, RegexOptions.None);
            return matchResult.Count > 0;
        }

        public static string ReplaceLinkText(string text)//过滤html,js,css代码
        {
            text = text.Trim();
            if (string.IsNullOrEmpty(text))
                return string.Empty;
            //text = Regex.Replace(text, "<head[^>]*>(?:.|[\r\n])*?</head>", "");
            text = Regex.Replace(text, "<script[^>]*>(?:.|[\r\n])*?</script>", "");
            //////text = Regex.Replace(text, "<style[^>]*>(?:.|[\r\n])*?</style>", "");
            text = Regex.Replace(text, "<a\\s+[^>]*href=['\"][^'\">]*['\"][^>]*>", string.Empty, RegexOptions.IgnoreCase); //<a ></a>
            //text = Regex.Replace(text, "[\\s]{2,}", " "); //两个或多个空格替换为一个
            //text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", ""); //<br> 
            //text = Regex.Replace(text, "\\&[a-zA-Z]{1,10};", "");
            //text = Regex.Replace(text, "<[^>]*>", "");

            ////text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", ""); //&nbsp;
            ////text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); //其它任何标记
            //text = text.Replace("'", "''");
            //text = text.Replace("\r\n", "");
            //text = text.Replace("  ", "");
            //text = text.Replace("\t", "");
            return text;
        }

        #endregion

        #region Page button

        private async void BtnPrevClick(object sender, RoutedEventArgs e)
        {
            if (_chapter != null)
            {
                _chapter = await ArticleService.Instance().GetChapter(_chapter.previewpage);
                await ChapterService.SaveChapterSession(_chapter);
                //var tran = new BookTranChapterInfo { CurrentChapter = _chapter };
                //if (_maxChapters != null)
                //    tran.MaxChapters = _maxChapters;

                Frame.Navigate(typeof(Chapter), _chapter.chapterid);
            }
        }

        private async void BtnNextClick(object sender, RoutedEventArgs e)
        {
            if (_chapter != null)
            {
                _chapter = await ArticleService.Instance().GetChapter(_chapter.nextpage);
                await ChapterService.SaveChapterSession(_chapter);
                //var tran = new BookTranChapterInfo { CurrentChapter = _chapter };
                //if (_maxChapters != null)
                //    tran.MaxChapters = _maxChapters;

                Frame.Navigate(typeof(Chapter), _chapter.chapterid);
            }
        }

        #endregion

        private async void HyperlinkButtonClick(object sender, RoutedEventArgs e)
        {
            if(hlbLink.Content.ToString().Equals("浏览原版本"))
            {
                var content = await GetHtmlContent();
                await ShowContent(content,false, true, false);
                hlbLink.Content = "浏览简化版";
            }
            else
            {
                Frame.Navigate(typeof(Chapter), _chapter.chapterid);
            }
        }
    }
}
